package com.whims.GC;


import java.util.Objects;

/**
 * 1：对象在GC时的自我拯救
 * 2：自救机会只有一次，因为一个对象的finalize方法最多只会被系统自动调用一次
 */
public class FinalizeEscapeGC {

    public static FinalizeEscapeGC SAVE_HOOK = null;

    public void isAlive(){
        System.out.println("我还活着");
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("execute finalize method .");
        FinalizeEscapeGC.SAVE_HOOK = this;
    }

    public static void main(String [] args) throws InterruptedException {
        SAVE_HOOK = new FinalizeEscapeGC();
        SOS();
        //第二次自救失败
        SOS();
    }

    //自救方法
    public static void SOS() throws InterruptedException {
        SAVE_HOOK = null;
        System.gc();
        //因为finalize方法优先级很低，暂停0.5秒等待
        Thread.sleep(500);
        if(Objects.nonNull(SAVE_HOOK)){
            SAVE_HOOK.isAlive();
        }else {
            System.out.println("已死");
        }
    }

}
